package com.jbm.jbmsupplier.zp.utils;

import android.content.Context;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.ListView;

import com.jbm.core.iface.IAcross;
import com.jbm.jbmsupplier.net.NetinterSend;
import com.jbm.jbmsupplier.zp.adapters.ChatMsgViewAdapter;
import com.jbm.jbmsupplier.zp.dao.RecordStrategy;
import com.jbm.jbmsupplier.zp.entity.ChatMsgEntity;
import com.jbm.jbmsupplier.zp.sqldata.MySqliteUtlis;
import com.jbm.onehome.common.OHInterface;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.jbm.jbmsupplier.zp.liaotian.MainActivity.cgid;
import static com.jbm.jbmsupplier.zp.utils.TableName.CHAT;
import static com.jbm.jbmsupplier.zp.utils.TableName.CHATGROUD;
import static com.jbm.jbmsupplier.zp.utils.TableName.RECENT;
import static com.jbm.jbmsupplier.zp.utils.TableName.sendIndex;

/**
 * 录音的
 */
public class AudioRecorder implements RecordStrategy {
    private final int SEND_AUDIO = 0001;
    private String user;
    public int dates;
    private MediaRecorder recorder;
    ChatMsgViewAdapter mAdapter;
    private String fileName;
    private String fileFolder = Environment.getExternalStorageDirectory().getPath() + "/TestRecord";
    private int toid;
    private int tag;//标识是不是群
    private int loginid;
    private String name;
    private ListView mListView;
    private boolean isRecording = false;
    private Context context;
    private List<ChatMsgEntity> mDataArrayss;
    ClassUser ClassUser;
    private String date;


    public AudioRecorder() {
    }

    public AudioRecorder(int toid, ChatMsgViewAdapter mAdapter, int loginid, String name, ListView mListView, Context context, List<ChatMsgEntity> mDataArrays, int tags) {
        this.name = name;
        this.loginid = loginid;
        this.toid = toid;
        this.mAdapter = mAdapter;
        this.mListView = mListView;
        this.context = context;
        this.tag = tags;
        this.mDataArrayss = mDataArrays;
        ClassUser = new ClassUser(context);
        user = CHAT + ClassUser.getLogin() + toid;
    }

    @Override
    public void ready() {
        // TODO Auto-generated method stub
        File file = new File(fileFolder);
        if (!file.exists()) {
            file.mkdir();
        }
        fileName = getCurrentDate();
        recorder = new MediaRecorder();
        recorder.setOutputFile(fileFolder + "/" + fileName + ".amr");
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置MediaRecorder的音频源为麦克风
        recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);// 设置MediaRecorder录制的音频格式
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);// 设置MediaRecorder录制音频的编码为amr
    }

    // 以当前时间作为文件名
    private String getCurrentDate() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HHmmss");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        String str = formatter.format(curDate);
        return str;
    }

    @Override
    public void start() {
        // TODO Auto-generated method stub
        if (!isRecording) {
            try {
                recorder.prepare();
                recorder.start();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            isRecording = true;
        }

    }

    @Override
    public void stop(boolean is) {
        // TODO Auto-generated method stub
        if (isRecording) {
            recorder.stop();
            recorder.release();
            isRecording = false;
            if (is == true) {
                try {
                    SendAudio();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private void SendAudio() throws IOException {

        NetinterSend netinterSend = new NetinterSend(handler);
        ChatMsgEntity entity = new ChatMsgEntity();
        date = DataFormate.formate(DataFormate.StringF, System.currentTimeMillis());
        entity.setDate(date);
        entity.setName(name + "");
        entity.setTo_id(toid);
        entity.setLocal_id(loginid);
        entity.setMediaName(fileFolder + "/" + fileName + ".amr");
        entity.setFlag(11);
        entity.setIsboolean("true");
        entity.setHead_portrait(OHInterface.getG_server().logo);
        mAdapter.notifyData(entity);
        mListView.setSelection(mListView.getCount() - 1);
        if (tag == 1) {
            netinterSend.SetSendAudio(cgid, SEND_AUDIO, toid, fileFolder + "/" + fileName + ".amr", fileName + ".amr");
            MySqliteUtlis.GetInstan(context).InsertGroadTable(CHATGROUD, name, OHInterface.getG_server().logo, getDate(), "", "", toid, -1, -1, -0, "", "", fileFolder + "/" + fileName + ".amr", "", 0, "", "", 11, cgid, 1, "true",ClassUser.getLogin());

        } else {
            netinterSend.SetSendAudio(-1, SEND_AUDIO, toid, fileFolder + "/" + fileName + ".amr", fileName + ".amr");
            MySqliteUtlis.GetInstan(context).StoringChatData(CHAT, toid, OHInterface.getG_server().logo, "语音", date, String.valueOf(toid), fileFolder + "/" + fileName + ".amr", fileFolder + "/" + fileName + ".amr", "", "", "", "", "", "", "", 11, 1, "true",ClassUser.getLogin());
            ArrayList<String> als = MySqliteUtlis.GetInstan(context).showaRecentContactsid(RECENT,toid,ClassUser.getLogin());
            if (!als.toString().contains(toid+"")) {
                MySqliteUtlis.GetInstan(context).StoringRecentID(RECENT , toid,ClassUser.getLogin(),date);
            }else if (als.toString()==null){
                MySqliteUtlis.GetInstan(context).StoringRecentID(RECENT , toid,ClassUser.getLogin(),date);

            }
        }
        sendIndex += 1;
    }

    private String getDate() {
        return DataFormate.formate(DataFormate.StringF, System.currentTimeMillis());
    }

    @Override
    public void deleteOldFile() {
        // TODO Auto-generated method stub
        File file = new File(fileFolder + "/" + fileName + ".amr");
        file.deleteOnExit();
    }

    @Override
    public double getAmplitude() {
        // TODO Auto-generated method stub
        if (!isRecording) {
            return 0;
        }
        return recorder.getMaxAmplitude();
    }

    @Override
    public String getFilePath() {
        // TODO Auto-generated method stub
        return fileFolder + "/" + fileName + ".amr";
    }

    @Override
    public void getSecondWhei(int date, int layout) {
        dates = date;
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SEND_AUDIO:
                    IAcross across = (IAcross) msg.obj;
                    if (across.m_code == 200) {
                        try {
                            mDataArrayss.get(sendIndex).setIsboolean("true");
                            mAdapter.notifyData(mDataArrayss);
                        } catch (Exception e) {
                        }
                    } else {
                        try {
                            if (tag == 1) {
                                MySqliteUtlis.GetInstan(context).UpdateErrMsg(CHATGROUD, cgid, date, "false",ClassUser.getLogin());
                                mDataArrayss = MySqliteUtlis.GetInstan(context).ShowGroadTable(CHATGROUD, cgid,ClassUser.getLogin());
                            } else {
                                MySqliteUtlis.GetInstan(context).Updateer(CHAT, "false", date,ClassUser.getLogin());
                                mDataArrayss.get(sendIndex).setIsboolean("false");
                            }

                            mAdapter.notifyData(mDataArrayss);
                        } catch (Exception e) {
                        }
                    }
                    break;

            }

        }
    };
}
